/**
 * Stores used during project add/edit
 */
import { defineStore } from 'pinia'
import getFormConfigStore from './formConfig'
import api from '@/api/index'
import { collectionHelpers } from './modelStore'
export const useProjectConfigStore = getFormConfigStore('project')

export const useProjectStore = defineStore('project', {
  state: () => ({
    loading: true,
    error: false,
    collection: [],
    projectId: null,
    item: {},
  }),
  actions: {
    setCurrentProjectId(projectId) {
      this.projectId = projectId
    },
    async loadProject(projectId = null) {
      projectId = projectId || this.projectId
      if (!projectId) {
        throw Error('no Id provided')
      }
      this.loading = true
      return api.projects
        .load(projectId)
        .then((item) => {
          this.loading = false
          this.error = false
          this.item = item
          return item
        })
        .catch(this.handleError)
    },
    async loadProjects(companyId, options) {
      this.loading = true
      return api.projects
        .getProjects(companyId, options)
        .then((result) => {
          let collection
          if (options.pageOptions && result.length == 2) {
            this.collectionMetaData = result[0]
            collection = result[1]
          } else {
            collection = result
          }
          this.loading = false
          this.error = ''
          this.collection = collection
          return collection
        })
        .catch(this.handleError)
    },
    async handleError(error) {
      this.loading = false
      this.error = error
      return Promise.reject(error)
    },
    async saveProject(data) {
      let projectId = this.projectId || data.id
      if (projectId) {
        return api.projects.update(data, projectId)
      } else {
        return this.createProject(data)
      }
    },
    async createProject(data) {
      if (data.id) {
        throw Error('Project already exists (has an id)')
      }
      const configStore = useProjectConfigStore()
      const companyId = configStore.getOptions('company_id')
      if (!companyId) {
        throw Error('Missing company_id')
      }
      api.projects.setCompanyId(companyId)
      return api.projects.create(data)
    },
    async updateProject(data, projectId) {
      if (!projectId) {
        throw Error('no Id provided')
      }
      return api.projects.update(data, projectId)
    },
  },
  getters: collectionHelpers('project'),
})
